import { useState, useEffect } from 'react';
import { Table, Input, Button, Form, Row, Col, Card, Space, App, Modal } from 'antd';
import { getApisList, deleteApi, addApi, updateApi, getApiById } from '@/api/api';
import AuthControl from '@/components/common/AuthControl';
import hasElementAuth from '@/utils/auth';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import ApiForm from './ApiForm';

const ApisIndex = () => {
  const [form] = Form.useForm();
  const [addEditForm] = Form.useForm();
  const { modal,message } = App.useApp();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditing, setIsEditing] = useState(false); // 只需要布尔值表示是否为编辑状态
  const [drawerLoading, setDrawerLoading] = useState(false);
  
  const getColumns = () => {
    const baseColumns = [
      {
        title: '权限名称',
        dataIndex: 'label',
        key: 'label'
      },
      {
        title: '授权标识符',
        dataIndex: 'code',
        key: 'code'
      }
    ];

    if(hasElementAuth(['edit','delete'])){
      baseColumns.push(
        {
          title: '操作',
          key: 'action',
          width: 250,
          render: (_, record) => (
            <Space>
              <AuthControl permission="edit">
                <Button icon={<EditOutlined />} onClick={() => openEditModal(record)}>编辑</Button>
              </AuthControl>
              <AuthControl permission="delete">
                <Button icon={<DeleteOutlined />} onClick={()=>deleteById(record.permissionId)} danger>删除</Button>
              </AuthControl>
            </Space >
          )
        }
      );
    }
    
    return baseColumns;
  };

  const [searchForm, setSearchForm] = useState({
    label: "",
    size: 10,
    current: 1
  });
  
  const [total, setTotal] = useState(0);
  const [tableData, setTableData] = useState([]);
  const [loading, setLoading] = useState(false);

  /**
   * 查询API列表
   */
  const searchApis = (formData) => {
    setLoading(true);
    const params = formData || searchForm;
    getApisList(params)
      .then(res => {
        if (res.data && res.data.others) {
          setTableData(res.data.others);
          setTotal(res.data.total || 0);
        } else {
          setTableData([]);
          setTotal(0);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };
  
  /**
   * 删除API
   */
  const deleteById = (id) => {
    modal.confirm({
      title: '确定要删除吗？',
      content: '此操作将永久删除该数据，请谨慎操作。',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setLoading(true);
        deleteApi({id:id}).then(() => {
          message.success( 'API权限已成功删除');
          searchApis();
          })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  };
  
  /**
   * 打开新增模态框
   */
  const openAddModal = () => {
    setIsEditing(false); // 设置为新增状态
    addEditForm.resetFields();
    setIsModalOpen(true);
  };
  
  /**
   * 打开编辑模态框
   */
  const openEditModal = (record) => {
    setDrawerLoading(true);
    setIsEditing(true); // 设置为编辑状态
    setIsModalOpen(true);
    
    // 调用接口获取详细信息
    getApiById({id: record.permissionId}).then(res => {
      if (res.data) {
        addEditForm.setFieldsValue({
          permissionId: res.data.permissionId,
          label: res.data.label,
          code: res.data.code,
          remark: res.data.remark
        });
      }
    })
    .finally(() => {
      setDrawerLoading(false);
    });
  };
  
  /**
   * 关闭模态框
   */
  const closeModal = () => {
    setIsModalOpen(false);
    addEditForm.resetFields();
    setIsEditing(false); // 重置为非编辑状态
  };
  
  /**
   * 保存API数据
   */
  const saveApiData = () => {
    addEditForm.validateFields().then(values => {
      setDrawerLoading(true);
      if (isEditing) {
        // 修改
        const updateData = {
          permissionId: values.permissionId,
          remark: values.remark
        };
        updateApi(updateData).then(() => {
          message.success( 'API权限信息已更新');
          closeModal();
          searchApis();
        }).finally(() => {
          setDrawerLoading(false);
        });
      } else {
        // 新增
        const addData = {
          label: values.label,
          code: values.code,
          remark: values.remark
        };
        addApi(addData).then(() => {
          message.success( '新API权限已添加');
          closeModal();
          searchApis();
        }).finally(() => {
          setDrawerLoading(false);
        });
      }
    })
  };

  useEffect(() => {
    searchApis();
  }, []);

  const handleTableChange = (pagination) => {
    const formData = {
      ...searchForm,
      current: pagination.current,
      size: pagination.pageSize
    };
    
    // 如果pageSize发生变化，重置到第一页
    if (pagination.pageSize !== searchForm.size) {
      formData.current = 1;
    }
    
    setSearchForm(formData);
    searchApis(formData);
  };

  const handleSearch = (values) => {
    const formData = {
      ...searchForm,
      label: values.label || "",
      current: 1 // 重置为第一页
    };
    setSearchForm(formData);
    searchApis(formData);
  };

  return (
    <Card>
      <AuthControl permission="search">
        <Form form={form} onFinish={handleSearch}>
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item name="label" label="权限名称">
                <Input placeholder="请输入权限名称" allowClear/>
              </Form.Item>
            </Col>
            <Col span={16} style={{ textAlign: 'right' }}>
              <Form.Item>
                  <Button type="primary" htmlType="submit" loading={loading} icon={<SearchOutlined />} style={{ marginRight: 8 }}>
                    查询
                  </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </AuthControl>
      <AuthControl permission="add">
        <Button loading={loading} type="primary" icon={<PlusOutlined />} style={{ marginBottom: 16 }} onClick={openAddModal}>
          添加
        </Button>
      </AuthControl>
      <Table 
        columns={getColumns()}
        dataSource={tableData} 
        rowKey="permissionId" 
        loading={loading}
        scroll={{ y: '45vh' }}
        pagination={{
          current: searchForm.current,
          pageSize: searchForm.size,
          total: total,
          showTotal: (total) => `共 ${total} 条数据`,
          showSizeChanger: true,
          pageSizeOptions: ['5','10', '20', '50', '100']
        }}
        onChange={handleTableChange}
      />
      
      {/* 新增/编辑模态框 */}
      <Modal
        title={isEditing ? "编辑权限" : "新增权限"}
        open={isModalOpen}
        onCancel={closeModal}
        confirmLoading={drawerLoading}
        footer={[
          <Button key="cancel" onClick={closeModal}>取消</Button>,
          <Button key="save" type="primary" onClick={saveApiData} loading={drawerLoading}>
            保存
          </Button>
        ]}
      >
        <ApiForm form={addEditForm} isEditing={isEditing} />
      </Modal>
    </Card>
  );
};

export default ApisIndex;